import 'dart:async';
import 'package:flutter/material.dart';

class AutoCarousel extends StatefulWidget {
  final List<Widget> children;
  final Duration autoPlayInterval;
  final Duration animationDuration;
  final bool autoPlay;
  final double height;
  final bool showIndicator;
  final Color indicatorColor;
  final Color activeIndicatorColor;
  final double indicatorSize;
  final double borderRadius;
  final bool enableInfiniteScroll;
  final Function(int)? onPageChanged;
  final Widget? customIndicator;
  final BoxFit imageFit;
  final EdgeInsets padding;

  const AutoCarousel({
    Key? key,
    required this.children,
    this.autoPlayInterval = const Duration(seconds: 3),
    this.animationDuration = const Duration(milliseconds: 300),
    this.autoPlay = true,
    this.height = 200,
    this.showIndicator = true,
    this.indicatorColor = Colors.white60,
    this.activeIndicatorColor = Colors.white,
    this.indicatorSize = 8.0,
    this.borderRadius = 0,
    this.enableInfiniteScroll = true,
    this.onPageChanged,
    this.customIndicator,
    this.imageFit = BoxFit.cover,
    this.padding = EdgeInsets.zero,
  }) : super(key: key);

  @override
  State<AutoCarousel> createState() => _AutoCarouselState();
}

// State 实现...（与前面类似，但添加了新功能）
class _AutoCarouselState extends State<AutoCarousel> {
  late PageController _pageController;
  Timer? _timer;
  int _currentPage = 0;
  bool _isUserScrolling = false;
  int get _actualItemCount => widget.enableInfiniteScroll
      ? widget.children.length * 1000
      : widget.children.length;

  @override
  void initState() {
    super.initState();
    _pageController = PageController(
      initialPage: widget.enableInfiniteScroll
          ? _actualItemCount ~/ 2
          : 0,
    );

    if (widget.autoPlay) {
      _startAutoPlay();
    }
  }

  @override
  void dispose() {
    _stopAutoPlay();
    _pageController.dispose();
    super.dispose();
  }

  void _startAutoPlay() {
    _timer = Timer.periodic(widget.autoPlayInterval, (timer) {
      if (!_isUserScrolling && mounted && _pageController.hasClients) {
        _pageController.nextPage(
          duration: widget.animationDuration,
          curve: Curves.easeInOut,
        );
      }
    });
  }

  void _stopAutoPlay() {
    _timer?.cancel();
    _timer = null;
  }

  int _getRealIndex(int position) {
    return position % widget.children.length;
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: widget.padding,
      child: Stack(
        children: [
          // 轮播内容
          ClipRRect(
            borderRadius: BorderRadius.circular(widget.borderRadius),
            child: SizedBox(
              height: widget.height,
              child: NotificationListener<ScrollNotification>(
                onNotification: (notification) {
                  if (notification is ScrollStartNotification) {
                    _isUserScrolling = true;
                    _stopAutoPlay();
                  } else if (notification is ScrollEndNotification) {
                    _isUserScrolling = false;
                    if (widget.autoPlay) {
                      _startAutoPlay();
                    }
                  }
                  return true;
                },
                child: PageView.builder(
                  controller: _pageController,
                  onPageChanged: (index) {
                    setState(() {
                      _currentPage = _getRealIndex(index);
                    });
                    widget.onPageChanged?.call(_currentPage);
                  },
                  itemCount: _actualItemCount,
                  itemBuilder: (context, index) {
                    final realIndex = _getRealIndex(index);
                    return GestureDetector(
                      onTap: () {
                        // 处理点击事件
                      },
                      child: widget.children[realIndex],
                    );
                  },
                ),
              ),
            ),
          ),

          // 自定义指示器或默认指示器
          if (widget.showIndicator)
            Positioned(
              bottom: 10,
              left: 0,
              right: 0,
              child: widget.customIndicator ?? _buildDefaultIndicator(),
            ),

          // 左右箭头导航（可选）
          if (widget.children.length > 1) ...[
            // 左箭头
            Positioned(
              left: 10,
              top: 0,
              bottom: 0,
              child: _buildNavigationButton(
                Icons.arrow_back_ios,
                    () => _pageController.previousPage(
                  duration: widget.animationDuration,
                  curve: Curves.easeInOut,
                ),
              ),
            ),
            // 右箭头
            Positioned(
              right: 10,
              top: 0,
              bottom: 0,
              child: _buildNavigationButton(
                Icons.arrow_forward_ios,
                    () => _pageController.nextPage(
                  duration: widget.animationDuration,
                  curve: Curves.easeInOut,
                ),
              ),
            ),
          ],
        ],
      ),
    );
  }

  Widget _buildDefaultIndicator() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: List.generate(
        widget.children.length,
            (index) => Container(
          width: widget.indicatorSize,
          height: widget.indicatorSize,
          margin: const EdgeInsets.symmetric(horizontal: 4),
          decoration: BoxDecoration(
            shape: BoxShape.circle,
            color: _currentPage == index
                ? widget.activeIndicatorColor
                : widget.indicatorColor,
          ),
        ),
      ),
    );
  }

  Widget _buildNavigationButton(IconData icon, VoidCallback onPressed) {
    return Center(
      child: Material(
        color: Colors.black26,
        shape: const CircleBorder(),
        child: InkWell(
          onTap: onPressed,
          customBorder: const CircleBorder(),
          child: Padding(
            padding: const EdgeInsets.all(8.0),
            child: Icon(
              icon,
              color: Colors.white,
              size: 24,
            ),
          ),
        ),
      ),
    );
  }
}